//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.imagemanager.util;

import android.app.IntentService;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.MergeCursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory.Options;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.os.Process;
import android.os.SystemClock;
import android.provider.MediaStore.Images.Media;
import android.provider.MediaStore.Video.Thumbnails;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.LongBuffer;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.http.conn.ClientConnectionManager;

public final class CacheService extends IntentService {
    public static final String ACTION_CACHE = "com.imagemanager.cache.action.CACHE";
    public static final DiskCache sAlbumCache = new DiskCache("local-album-cache");
    public static final DiskCache sMetaAlbumCache = new DiskCache("local-meta-cache");
    public static final DiskCache sSkipThumbnailIds = new DiskCache("local-skip-cache");
    public static final DiskCache sThumbnailCache = new DiskCache("local-image-thumbs");
    public static final DiskCache sThumbnailCacheVideo = new DiskCache("local-video-thumbs");
    public static final String CAMERA_STRING = "Camera";
    public static final String DOWNLOAD_STRING = "download";
    public static final String CAMERA_BUCKET_NAME = Environment.getExternalStorageDirectory().toString() + "/DCIM/" + "Camera";
    public static final String DOWNLOAD_BUCKET_NAME = Environment.getExternalStorageDirectory().toString() + "/" + "download";
    public static final int CAMERA_BUCKET_ID;
    public static final int DOWNLOAD_BUCKET_ID;
    public static ArrayList<String> dcimFolderList;
    public static Object lock = new Object();
    private static final String TAG = "CacheService";
    private static ImageList sList;
    private static final int THUMBNAILER_WAIT_IN_MS = 2000;
    private static final int DEFAULT_THUMBNAIL_WIDTH = 128;
    private static final int DEFAULT_THUMBNAIL_HEIGHT = 96;
    public static String DEFAULT_IMAGE_SORT_ORDER;
    public static final String DEFAULT_VIDEO_SORT_ORDER = "datetaken ASC";
    public static final String DEFAULT_BUCKET_SORT_ORDER = "upper(bucket_display_name) ASC";
    public static final int BUCKET_ID_INDEX = 0;
    public static final int BUCKET_NAME_INDEX = 1;
    public static final String[] BUCKET_PROJECTION_IMAGES;
    public static final String[] BUCKET_PROJECTION_VIDEOS;
    public static final int THUMBNAIL_ID_INDEX = 0;
    public static final int THUMBNAIL_DATE_MODIFIED_INDEX = 1;
    public static final int THUMBNAIL_DATA_INDEX = 2;
    public static final int THUMBNAIL_ORIENTATION_INDEX = 2;
    public static final String[] THUMBNAIL_PROJECTION;
    public static final String[] SENSE_PROJECTION;
    public static final int MEDIA_ID_INDEX = 0;
    public static final int MEDIA_CAPTION_INDEX = 1;
    public static final int MEDIA_MIME_TYPE_INDEX = 2;
    public static final int MEDIA_LATITUDE_INDEX = 3;
    public static final int MEDIA_LONGITUDE_INDEX = 4;
    public static final int MEDIA_DATE_TAKEN_INDEX = 5;
    public static final int MEDIA_DATE_ADDED_INDEX = 6;
    public static final int MEDIA_DATE_MODIFIED_INDEX = 7;
    public static final int MEDIA_DATA_INDEX = 8;
    public static final int MEDIA_ORIENTATION_OR_DURATION_INDEX = 9;
    public static final int MEDIA_BUCKET_ID_INDEX = 10;
    public static final String[] PROJECTION_IMAGES;
    private static final String[] PROJECTION_VIDEOS;
    public static final String BASE_CONTENT_STRING_IMAGES;
    public static final String BASE_CONTENT_STRING_VIDEOS;
    private static final AtomicReference<Thread> CACHE_THREAD;
    private static final AtomicReference<Thread> THUMBNAIL_THREAD;
    private static final int ALBUM_CACHE_METADATA_INDEX = -1;
    private static final int ALBUM_CACHE_DIRTY_INDEX = -2;
    private static final int ALBUM_CACHE_INCOMPLETE_INDEX = -3;
    private static final int ALBUM_CACHE_DIRTY_BUCKET_INDEX = -4;
    private static final int ALBUM_CACHE_LOCALE_INDEX = -5;
    private static final DateFormat mDateFormat;
    private static final DateFormat mAltDateFormat;
    private static final byte[] sDummyData;
    private static boolean QUEUE_DIRTY_SET;
    private static boolean QUEUE_DIRTY_ALL;
    private static boolean QUEUE_DIRTY_SENSE;

    static {
        CAMERA_BUCKET_ID = getBucketId(CAMERA_BUCKET_NAME);
        DOWNLOAD_BUCKET_ID = getBucketId(DOWNLOAD_BUCKET_NAME);
        sList = null;
        DEFAULT_IMAGE_SORT_ORDER = "date_added ASC";
        BUCKET_PROJECTION_IMAGES = new String[]{"bucket_id", "bucket_display_name"};
        BUCKET_PROJECTION_VIDEOS = new String[]{"bucket_id", "bucket_display_name"};
        THUMBNAIL_PROJECTION = new String[]{"_id", "date_modified", "_data", "orientation"};
        SENSE_PROJECTION = new String[]{"bucket_id", "MAX(date_added), COUNT(*)"};
        PROJECTION_IMAGES = new String[]{"_id", "title", "mime_type", "latitude", "longitude", "datetaken", "date_added", "date_modified", "_data", "orientation", "bucket_id"};
        PROJECTION_VIDEOS = new String[]{"_id", "title", "mime_type", "latitude", "longitude", "datetaken", "date_added", "date_modified", "_data", "duration", "bucket_id"};
        BASE_CONTENT_STRING_IMAGES = Media.EXTERNAL_CONTENT_URI.toString() + "/";
        BASE_CONTENT_STRING_VIDEOS = android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI.toString() + "/";
        CACHE_THREAD = new AtomicReference();
        THUMBNAIL_THREAD = new AtomicReference();
        mDateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
        mAltDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        sDummyData = new byte[]{1};
    }

    public static void setImageOrderAsc(boolean flag) {
        if(flag) {
            DEFAULT_IMAGE_SORT_ORDER = "date_added ASC";
        } else {
            DEFAULT_IMAGE_SORT_ORDER = "date_added DESC";
        }

    }

    public static final String getCachePath(String subFolderName) {
        return Environment.getExternalStorageDirectory() + "/Android/data/com.imagemanager.util/cache/" + subFolderName;
    }

    public static final String getCachePath() {
        return Environment.getExternalStorageDirectory() + "/Android/data/com.imagemanager.util/";
    }

    public static final void startCache(Context context, boolean checkthumbnails) {
//        Locale locale = getLocaleForAlbumCache();
//        Locale defaultLocale = Locale.getDefault();
//        if(locale == null || !locale.equals(defaultLocale)) {
//            sAlbumCache.deleteAll();
//            putLocaleForAlbumCache(defaultLocale);
//        }
//
//        Intent intent = new Intent("com.imagemanager.cache.action.CACHE", (Uri)null, context, CacheService.class);
//        intent.putExtra("checkthumbnails", checkthumbnails);
//        context.startService(intent);
    }

    public static final boolean isCacheReady(boolean onlyMediaSets) {
        return onlyMediaSets?sAlbumCache.get(-1L, 0L) != null && sAlbumCache.get(-2L, 0L) == null:sAlbumCache.get(-1L, 0L) != null && sAlbumCache.get(-2L, 0L) == null && sAlbumCache.get(-3L, 0L) == null;
    }

    public static final boolean isCacheReady(long setId) {
        boolean isReady = sAlbumCache.get(-1L, 0L) != null && sAlbumCache.get(-2L, 0L) == null && sAlbumCache.get(-3L, 0L) == null;
        if(!isReady) {
            return isReady;
        } else {
            byte[] existingData = sAlbumCache.get(-4L, 0L);
            if(existingData != null && existingData.length > 0) {
                long[] ids = toLongArray(existingData);
                int numIds = ids.length;

                for(int i = 0; i < numIds; ++i) {
                    if(ids[i] == setId) {
                        return false;
                    }
                }
            }

            return true;
        }
    }

    public static final boolean isPresentInCache(long setId) {
        return sAlbumCache.get(setId, 0L) != null;
    }

    public static final void markDirty(final Context context) {
        sList = null;
        sAlbumCache.put(-2L, sDummyData, 0L);
        if(CACHE_THREAD.get() == null) {
            QUEUE_DIRTY_SENSE = false;
            QUEUE_DIRTY_ALL = false;
            QUEUE_DIRTY_SET = false;
            restartThread(CACHE_THREAD, "CacheRefresh", new Runnable() {
                public void run() {
                    CacheService.refresh(context);
                    CacheService.processQueuedDirty(context);
                }
            });
        } else {
            QUEUE_DIRTY_ALL = true;
        }

    }

    public static final void markDirtyImmediate(long id) {
        if(id != -1L) {
            sList = null;
            byte[] data = longToByteArray(id);
            byte[] existingData = sAlbumCache.get(-4L, 0L);
            if(existingData != null && existingData.length > 0) {
                long[] ids = toLongArray(existingData);
                int numIds = ids.length;

                for(int i = 0; i < numIds; ++i) {
                    if(ids[i] == id) {
                        return;
                    }
                }

                data = concat(data, existingData);
            }

            sAlbumCache.put(-4L, data, 0L);
        }
    }

    public static final void markDirty(final Context context, long id) {
        markDirtyImmediate(id);
        if(CACHE_THREAD.get() == null) {
            QUEUE_DIRTY_SET = false;
            restartThread(CACHE_THREAD, "CacheRefreshDirtySets", new Runnable() {
                public void run() {
                    CacheService.refreshDirtySets(context);
                    CacheService.processQueuedDirty(context);
                }
            });
        } else {
            QUEUE_DIRTY_SET = true;
        }

    }

    public static final boolean setHasItems(ContentResolver cr, long setId) {
        Uri uriImages = Media.EXTERNAL_CONTENT_URI;
        Uri uriVideos = android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        StringBuffer whereString = new StringBuffer("bucket_id=" + setId);

        try {
            Cursor cursorImages = cr.query(uriImages, BUCKET_PROJECTION_IMAGES, whereString.toString(), (String[])null, (String)null);
            if(cursorImages != null && cursorImages.getCount() > 0) {
                cursorImages.close();
                return true;
            }

            Cursor cursorVideos = cr.query(uriVideos, BUCKET_PROJECTION_VIDEOS, whereString.toString(), (String[])null, (String)null);
            if(cursorVideos != null && cursorVideos.getCount() > 0) {
                cursorVideos.close();
                return true;
            }
        } catch (Exception var8) {
            ;
        }

        return false;
    }

    public static ArrayList<MediaSet> loadMediaSets(boolean includeImages, boolean includeVideos) {
        ArrayList<MediaSet> mMediaSets = new ArrayList();

        for(int timeElapsed = 0; !isCacheReady(true) && timeElapsed < 10000; timeElapsed += 300) {
            try {
                Thread.sleep(300L);
            } catch (InterruptedException var16) {
                return mMediaSets;
            }
        }

        byte[] albumData = sAlbumCache.get(-1L, 0L);
        if(albumData != null && albumData.length > 0) {
            DataInputStream dis = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(albumData), 256));

            try {
                int numAlbums = dis.readInt();

                for(int i = 0; i < numAlbums; ++i) {
                    long setId = dis.readLong();
                    String name = Utils.readUTF(dis);
                    boolean hasImages = dis.readBoolean();
                    boolean hasVideos = dis.readBoolean();
                    MediaSet mediaSet = getMediaSet(setId, mMediaSets);
                    if(mediaSet == null) {
                        mediaSet = new MediaSet();
                        mediaSet.mId = setId;
                        if(dcimFolderList.size() > 0) {
                            Iterator var15 = dcimFolderList.iterator();

                            while(var15.hasNext()) {
                                String path = (String)var15.next();
                                if(setId == (long)getBucketId(path)) {
                                    mediaSet.isDcim = true;
                                    break;
                                }
                            }
                        }

                        mediaSet = loadMediaItemsIntoMediaFeed(mediaSet, includeImages, includeVideos);
                        mMediaSets.add(mediaSet);
                    }

                    if(includeImages && hasImages || includeVideos && hasVideos) {
                        mediaSet.mName = name;
                        mediaSet.mHasImages = hasImages;
                        mediaSet.mHasVideos = hasVideos;
                        mediaSet.mPicasaAlbumId = -1L;
                        mediaSet.generateTitle(true);
                    }
                }
            } catch (IOException var17) {
                sAlbumCache.deleteAll();
                putLocaleForAlbumCache(Locale.getDefault());
                return mMediaSets;
            }
        }

        return mMediaSets;
    }

    private static MediaSet getMediaSet(long setId, ArrayList<MediaSet> mMediaSets) {
        try {
            int mMediaSetsSize = mMediaSets.size();

            for(int i = 0; i < mMediaSetsSize; ++i) {
                if(((MediaSet)mMediaSets.get(i)).mId == setId) {
                    return (MediaSet)mMediaSets.get(i);
                }
            }

            return null;
        } catch (Exception var5) {
            return null;
        }
    }

    public static MediaSet loadMediaItemsIntoMediaFeed(MediaSet set, boolean includeImages, boolean includeVideos) {
        int timeElapsed = 0;

        for(Object var4 = null; !isCacheReady(set.mId) && timeElapsed < 30000; timeElapsed += 300) {
            try {
                Thread.sleep(300L);
            } catch (InterruptedException var11) {
                return set;
            }
        }

        byte[] albumData = sAlbumCache.get(set.mId, 0L);
        if(albumData != null && set.mNumItemsLoaded < set.getNumExpectedItems()) {
            DataInputStream dis = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(albumData), 256));

            try {
                int numItems = dis.readInt();
                Log.i("CacheService", "Loading " + numItems + " into set " + set.mName + ":" + set);
                set.setNumExpectedItems(numItems);
                set.mMinTimestamp = dis.readLong();
                set.mMaxTimestamp = dis.readLong();

                for(int i = 0; i < numItems; ++i) {
                    MediaItem item = new MediaItem();
                    item.mId = dis.readLong();
                    item.mCaption = Utils.readUTF(dis);
                    item.mMimeType = Utils.readUTF(dis);
                    item.setMediaType(dis.readInt());
                    item.mLatitude = dis.readDouble();
                    item.mLongitude = dis.readDouble();
                    item.mDateTakenInMs = dis.readLong();
                    item.mTriedRetrievingExifDateTaken = dis.readBoolean();
                    item.mDateAddedInSec = dis.readLong();
                    item.mDateModifiedInSec = dis.readLong();
                    item.mDurationInSec = dis.readInt();
                    item.mRotation = (float)dis.readInt();
                    item.mFilePath = Utils.readUTF(dis);
                    int itemMediaType = item.getMediaType();
                    if(itemMediaType == 0 && includeImages || itemMediaType == 1 && includeVideos) {
                        String baseUri = itemMediaType == 0?BASE_CONTENT_STRING_IMAGES:BASE_CONTENT_STRING_VIDEOS;
                        item.mContentUri = baseUri + item.mId;
                    }

                    item.mParentMediaSet = set;
                    set.addItem(item);
                }

                dis.close();
            } catch (IOException var12) {
                Log.e("CacheService", "Error loading items for album " + set.mName);
                sAlbumCache.deleteAll();
                putLocaleForAlbumCache(Locale.getDefault());
            }
        } else {
            Log.d("CacheService", "No items found for album " + set.mName);
        }

        set.updateNumExpectedItems();
        set.generateTitle(true);
        return set;
    }

    public static final void populateVideoItemFromCursor(MediaItem item, ContentResolver cr, Cursor cursor, String baseUri) {
        item.setMediaType(1);
        populateMediaItemFromCursor(item, cr, cursor, baseUri);
    }

    public static final void populateMediaItemFromCursor(MediaItem item, ContentResolver cr, Cursor cursor, String baseUri) {
        item.mId = cursor.getLong(0);
        item.mCaption = cursor.getString(1);
        item.mMimeType = cursor.getString(2);
        item.mLatitude = cursor.getDouble(3);
        item.mLongitude = cursor.getDouble(4);
        item.mDateTakenInMs = cursor.getLong(5);
        item.mDateAddedInSec = cursor.getLong(6);
        item.mDateModifiedInSec = cursor.getLong(7);
        if(item.mDateTakenInMs == item.mDateModifiedInSec) {
            item.mDateTakenInMs = item.mDateModifiedInSec * 1000L;
        }

        item.mFilePath = cursor.getString(8);
        if(baseUri != null) {
            item.mContentUri = baseUri + item.mId;
        }

        int itemMediaType = item.getMediaType();
        long dateTaken = fetchDateTaken(item);
        if(dateTaken != -1L && item.mContentUri != null) {
            item.mDateTakenInMs = dateTaken;
            ContentValues values = new ContentValues();
            if(itemMediaType == 1) {
                values.put("datetaken", Long.valueOf(item.mDateTakenInMs));
            } else {
                values.put("datetaken", Long.valueOf(item.mDateTakenInMs));
            }

            try {
                cr.update(Uri.parse(item.mContentUri), values, (String)null, (String[])null);
            } catch (Exception var9) {
                ;
            }
        }

        int orientationDurationValue = cursor.getInt(9);
        if(itemMediaType == 0) {
            item.mRotation = (float)orientationDurationValue;
        } else {
            item.mDurationInSec = orientationDurationValue;
        }

    }

    public static final long fetchDateTaken(MediaItem item) {
        if(!item.isDateTakenValid() && !item.mTriedRetrievingExifDateTaken && (item.mFilePath.endsWith(".jpg") || item.mFilePath.endsWith(".jpeg"))) {
            try {
                ExifInterface exif = new ExifInterface(item.mFilePath);
                String dateTakenStr = exif.getAttribute("DateTime");
                if(dateTakenStr != null) {
                    try {
                        Date dateTaken = mDateFormat.parse(dateTakenStr);
                        return dateTaken.getTime();
                    } catch (ParseException var6) {
                        try {
                            Date dateTaken = mAltDateFormat.parse(dateTakenStr);
                            return dateTaken.getTime();
                        } catch (ParseException var5) {
                            Log.i("CacheService", "Unable to parse date out of string - " + dateTakenStr);
                        }
                    }
                }
            } catch (Exception var7) {
                Log.i("CacheService", "Error reading Exif information, probably not a jpeg.");
            }

            item.mTriedRetrievingExifDateTaken = true;
        }

        return -1L;
    }

    public static final byte[] queryThumbnail(Context context, long thumbId, long origId, boolean isVideo, long timestamp) {
        DiskCache thumbnailCache = isVideo?sThumbnailCacheVideo:sThumbnailCache;
        return queryThumbnail(context, thumbId, origId, isVideo, thumbnailCache, timestamp);
    }

    public static final ImageList getImageList(Context context) {
        if(sList != null) {
            return sList;
        } else {
            ImageList list = new ImageList();
            Uri uriImages = Media.EXTERNAL_CONTENT_URI;
            ContentResolver cr = context.getContentResolver();

            try {
                Cursor cursorImages = cr.query(uriImages, THUMBNAIL_PROJECTION, (String)null, (String[])null, (String)null);
                if(cursorImages != null && cursorImages.moveToFirst()) {
                    int size = cursorImages.getCount();
                    long[] ids = new long[size];
                    long[] thumbnailIds = new long[size];
                    long[] timestamp = new long[size];
                    int[] orientation = new int[size];
                    int ctr = 0;

                    while(!Thread.interrupted()) {
                        ids[ctr] = cursorImages.getLong(0);
                        timestamp[ctr] = cursorImages.getLong(1);
                        thumbnailIds[ctr] = Utils.Crc64Long(cursorImages.getString(2));
                        orientation[ctr] = cursorImages.getInt(2);
                        ++ctr;
                        if(!cursorImages.moveToNext()) {
                            break;
                        }
                    }

                    cursorImages.close();
                    list.ids = ids;
                    list.thumbids = thumbnailIds;
                    list.timestamp = timestamp;
                    list.orientation = orientation;
                }
            } catch (Exception var11) {
                ;
            }

            if(sList == null) {
                sList = list;
            }

            return list;
        }
    }

    private static final byte[] queryThumbnail(Context context, long thumbId, long origId, boolean isVideo, DiskCache thumbnailCache, long timestamp) {
        Thread thumbnailThread = (Thread)THUMBNAIL_THREAD.getAndSet(null);
        if(thumbnailThread != null) {
            thumbnailThread.interrupt();
        }

        byte[] bitmap = thumbnailCache.get(thumbId, timestamp);
        if(bitmap == null) {
            long time = SystemClock.uptimeMillis();
            bitmap = buildThumbnailForId(context, thumbnailCache, thumbId, origId, isVideo, 128, 96, timestamp);
            Log.i("CacheService", "Built thumbnail and screennail for " + origId + " in " + (SystemClock.uptimeMillis() - time));
        }

        return bitmap;
    }

    private static final void buildThumbnails(Context context) {
        Log.i("CacheService", "Preparing DiskCache for all thumbnails.");
        ImageList list = getImageList(context);
        int size = list.ids == null?0:list.ids.length;
        long[] ids = list.ids;
        long[] timestamp = list.timestamp;
        long[] thumbnailIds = list.thumbids;
        DiskCache thumbnailCache = sThumbnailCache;

        for(int i = 0; i < size; ++i) {
            if(Thread.interrupted()) {
                return;
            }

            long id = ids[i];
            long timeModifiedInSec = timestamp[i];
            long thumbnailId = thumbnailIds[i];
            if(!isInThumbnailerSkipList(thumbnailId) && !thumbnailCache.isDataAvailable(thumbnailId, timeModifiedInSec * 1000L)) {
                byte[] retVal = buildThumbnailForId(context, thumbnailCache, thumbnailId, id, false, 128, 96, timeModifiedInSec * 1000L);
                if(retVal == null || retVal.length == 0) {
                    addToThumbnailerSkipList(thumbnailId);
                }
            }
        }

        Log.i("CacheService", "DiskCache ready for all thumbnails.");
    }

    private static void addToThumbnailerSkipList(long thumbnailId) {
        sSkipThumbnailIds.put(thumbnailId, sDummyData, 0L);
        sSkipThumbnailIds.flush();
    }

    private static boolean isInThumbnailerSkipList(long thumbnailId) {
        if(sSkipThumbnailIds.isDataAvailable(thumbnailId, 0L)) {
            byte[] data = sSkipThumbnailIds.get(thumbnailId, 0L);
            if(data.length > 0) {
                return true;
            }
        }

        return false;
    }

    private static final byte[] buildThumbnailForId(final Context context, DiskCache thumbnailCache, long thumbId, final long origId, boolean isVideo, int thumbnailWidth, int thumbnailHeight, long timestamp) {
        if(origId == -1L) {
            return null;
        } else {
            try {
                Bitmap bitmap = null;
                Thread.sleep(1L);
                if(!isVideo) {
                    String uriString = BASE_CONTENT_STRING_IMAGES + origId;
                    UriTexture.invalidateCache(thumbId, 1024);

                    try {
                        bitmap = UriTexture.createFromUri(context, uriString, 1024, 1024, thumbId, (ClientConnectionManager)null);
                    } catch (Exception var14) {
                        return null;
                    }
                } else {
                    (new Thread() {
                        public void run() {
                            try {
                                Thread.sleep(5000L);
                            } catch (InterruptedException var3) {
                                ;
                            }

                            try {
                                Thumbnails.cancelThumbnailRequest(context.getContentResolver(), origId);
                            } catch (Exception var2) {
                                ;
                            }

                        }
                    }).start();
                    bitmap = Thumbnails.getThumbnail(context.getContentResolver(), origId, 3, (Options)null);
                }

                if(bitmap == null) {
                    return null;
                } else {
                    byte[] retVal = writeBitmapToCache(thumbnailCache, thumbId, origId, bitmap, thumbnailWidth, thumbnailHeight, timestamp);
                    return retVal;
                }
            } catch (InterruptedException var16) {
                return null;
            }
        }
    }

    public static final byte[] writeBitmapToCache(DiskCache thumbnailCache, long thumbId, long origId, Bitmap bitmap, int thumbnailWidth, int thumbnailHeight, long timestamp) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int focusX = width / 2;
        int focusY = height / 2;
        int cropX;
        int cropY;
        int cropWidth;
        int cropHeight;
        float scaleFactor;
        if(thumbnailWidth * height < thumbnailHeight * width) {
            cropWidth = thumbnailWidth * height / thumbnailHeight;
            cropX = Math.max(0, Math.min(focusX - cropWidth / 2, width - cropWidth));
            cropY = 0;
            cropHeight = height;
            scaleFactor = (float)thumbnailHeight / (float)height;
        } else {
            cropHeight = thumbnailHeight * width / thumbnailWidth;
            cropY = Math.max(0, Math.min(focusY - cropHeight / 2, height - cropHeight));
            cropX = 0;
            cropWidth = width;
            scaleFactor = (float)thumbnailWidth / (float)width;
        }

        Bitmap finalBitmap = Bitmap.createBitmap(thumbnailWidth, thumbnailHeight, Config.RGB_565);
        Canvas canvas = new Canvas(finalBitmap);
        Paint paint = new Paint();
        paint.setFilterBitmap(true);
        canvas.drawColor(0);
        canvas.drawBitmap(bitmap, new Rect(cropX, cropY, cropX + cropWidth, cropY + cropHeight), new Rect(0, 0, thumbnailWidth, thumbnailHeight), paint);
        bitmap.recycle();
        ByteArrayOutputStream cacheOutput = new ByteArrayOutputStream(16384);
        DataOutputStream dataOutput = new DataOutputStream(cacheOutput);
        byte[] retVal = null;

        try {
            dataOutput.writeLong(origId);
            dataOutput.writeShort((int)((float)(focusX - cropX) * scaleFactor));
            dataOutput.writeShort((int)((float)(focusY - cropY) * scaleFactor));
            dataOutput.flush();
            finalBitmap.compress(CompressFormat.JPEG, 80, cacheOutput);
            retVal = cacheOutput.toByteArray();
            synchronized(thumbnailCache) {
                thumbnailCache.put(thumbId, retVal, timestamp);
            }

            cacheOutput.close();
            finalBitmap.recycle();
        } catch (Exception var27) {
            ;
        }

        return retVal;
    }

    public CacheService() {
        super("CacheService");
    }

    protected void onHandleIntent(Intent intent) {
        Log.i("CacheService", "Starting CacheService");
        if(Environment.getExternalStorageState() == "bad_removal") {
            sAlbumCache.deleteAll();
            putLocaleForAlbumCache(Locale.getDefault());
        }

        this.startNewCacheThread();
        if(intent.getBooleanExtra("checkthumbnails", false)) {
            startNewThumbnailThread(this);
        } else {
            Thread existingThread = (Thread)THUMBNAIL_THREAD.getAndSet(null);
            if(existingThread != null) {
                existingThread.interrupt();
            }
        }

    }

    private static final void putLocaleForAlbumCache(Locale locale) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);

        try {
            Utils.writeUTF(dos, locale.getCountry());
            Utils.writeUTF(dos, locale.getLanguage());
            Utils.writeUTF(dos, locale.getVariant());
            dos.flush();
            bos.flush();
            byte[] data = bos.toByteArray();
            sAlbumCache.put(-5L, data, 0L);
            sAlbumCache.flush();
            dos.close();
            bos.close();
        } catch (IOException var4) {
            Log.i("CacheService", "Error writing locale to cache.");
        }

    }

    private static final Locale getLocaleForAlbumCache() {
        byte[] data = sAlbumCache.get(-5L, 0L);
        if(data != null && data.length > 0) {
            ByteArrayInputStream bis = new ByteArrayInputStream(data);
            DataInputStream dis = new DataInputStream(bis);

            try {
                String country = Utils.readUTF(dis);
                if(country == null) {
                    country = "";
                }

                String language = Utils.readUTF(dis);
                if(language == null) {
                    language = "";
                }

                String variant = Utils.readUTF(dis);
                if(variant == null) {
                    variant = "";
                }

                Locale locale = new Locale(language, country, variant);
                dis.close();
                bis.close();
                return locale;
            } catch (IOException var7) {
                Log.i("CacheService", "Error reading locale from cache.");
                return null;
            }
        } else {
            return null;
        }
    }

    private static final void restartThread(final AtomicReference<Thread> threadRef, String name, final Runnable action) {
        Thread newThread = new Thread() {
            public void run() {
                try {
                    action.run();
                } finally {
                    threadRef.compareAndSet(this, null);
                }

            }
        };
        newThread.setName(name);
        newThread.start();
        Thread existingThread = (Thread)threadRef.getAndSet(newThread);
        if(existingThread != null) {
            existingThread.interrupt();
        }

    }

    public static final void startNewThumbnailThread(final Context context) {
        restartThread(THUMBNAIL_THREAD, "ThumbnailRefresh", new Runnable() {
            public void run() {
                Process.setThreadPriority(10);

                try {
                    Thread.sleep(2000L);
                } catch (InterruptedException var2) {
                    return;
                }

                CacheService.buildThumbnails(context);
            }
        });
    }

    private void startNewCacheThread() {
        restartThread(CACHE_THREAD, "CacheRefresh", new Runnable() {
            public void run() {
                CacheService.refresh(CacheService.this);
            }
        });
    }

    private static final byte[] concat(byte[] A, byte[] B) {
        byte[] C = new byte[A.length + B.length];
        System.arraycopy(A, 0, C, 0, A.length);
        System.arraycopy(B, 0, C, A.length, B.length);
        return C;
    }

    private static final long[] toLongArray(byte[] data) {
        ByteBuffer bBuffer = ByteBuffer.wrap(data);
        LongBuffer lBuffer = bBuffer.asLongBuffer();
        int numLongs = lBuffer.capacity();
        long[] retVal = new long[numLongs];

        for(int i = 0; i < numLongs; ++i) {
            retVal[i] = lBuffer.get(i);
        }

        return retVal;
    }

    private static final byte[] longToByteArray(long l) {
        byte[] bArray = new byte[8];
        ByteBuffer bBuffer = ByteBuffer.wrap(bArray);
        LongBuffer lBuffer = bBuffer.asLongBuffer();
        lBuffer.put(0, l);
        return bArray;
    }

    private static final byte[] longArrayToByteArray(long[] l) {
        byte[] bArray = new byte[8 * l.length];
        ByteBuffer bBuffer = ByteBuffer.wrap(bArray);
        LongBuffer lBuffer = bBuffer.asLongBuffer();
        int numLongs = l.length;

        for(int i = 0; i < numLongs; ++i) {
            lBuffer.put(i, l[i]);
        }

        return bArray;
    }

    private static final void refresh(Context context) {
        Log.i("CacheService", "Refreshing cache.");
        sAlbumCache.deleteAll();
        getDcimFolders();
        putLocaleForAlbumCache(Locale.getDefault());
        ArrayList<MediaSet> sets = new ArrayList();
        LongSparseArray<MediaSet> acceleratedSets = new LongSparseArray();
        Log.i("CacheService", "Building albums.");
        Uri uriImages = Media.EXTERNAL_CONTENT_URI.buildUpon().appendQueryParameter("distinct", "true").build();
        ContentResolver cr = context.getContentResolver();

        try {
            Cursor cursorImages = cr.query(uriImages, BUCKET_PROJECTION_IMAGES, (String)null, (String[])null, "upper(bucket_display_name) ASC");
            Cursor[] cursors = new Cursor[]{cursorImages};
            SortCursor sortCursor = new SortCursor(cursors, "bucket_display_name", 0, true);

            try {
                if(sortCursor != null && sortCursor.moveToFirst()) {
                    sets.ensureCapacity(sortCursor.getCount());
                    acceleratedSets = new LongSparseArray(sortCursor.getCount());
                    if(dcimFolderList.size() == 0) {
                        MediaSet cameraSet = new MediaSet();
                        cameraSet.mId = (long)CAMERA_BUCKET_ID;
                        cameraSet.mName = "相机";
                        cameraSet.isDcim = true;
                        sets.add(cameraSet);
                        acceleratedSets.put(cameraSet.mId, cameraSet);
                    }

                    while(true) {
                        if(Thread.interrupted()) {
                            return;
                        }

                        long setId = sortCursor.getLong(0);
                        MediaSet mediaSet = findSet(setId, acceleratedSets);
                        if(mediaSet == null) {
                            mediaSet = new MediaSet();
                            if(dcimFolderList.size() > 0) {
                                Iterator var12 = dcimFolderList.iterator();

                                while(var12.hasNext()) {
                                    String path = (String)var12.next();
                                    if(setId == (long)getBucketId(path)) {
                                        mediaSet.isDcim = true;
                                        break;
                                    }
                                }
                            }

                            mediaSet.mId = setId;
                            mediaSet.mName = sortCursor.getString(1);
                            sets.add(mediaSet);
                            acceleratedSets.put(setId, mediaSet);
                        }

                        mediaSet.mHasImages |= sortCursor.getCurrentCursorIndex() == 0;
                        mediaSet.mHasVideos |= sortCursor.getCurrentCursorIndex() == 1;
                        if(!sortCursor.moveToNext()) {
                            sortCursor.close();
                            break;
                        }
                    }
                }
            } finally {
                if(sortCursor != null) {
                    sortCursor.close();
                }

            }

            sAlbumCache.put(-3L, sDummyData, 0L);
            writeSetsToCache(sets);
            Log.i("CacheService", "Done building albums.");
            populateMediaItemsForSets(context, sets, acceleratedSets, false);
        } catch (Exception var17) {
            ;
        }

        sAlbumCache.delete(-3L);
    }

    public static void getDcimFolders() {
        synchronized (lock){
            if(dcimFolderList == null) {
                dcimFolderList = new ArrayList<>();
            }

            boolean sdCardExist = Environment.getExternalStorageState().equals("mounted");
            File file = new File(Environment.getExternalStorageDirectory(), "/DCIM/");
            addCustomFolders(file);
            File file2 = new File(Environment.getExternalStorageDirectory(), "/dcim/");
            addCustomFolders(file2);
        }
    }

    public static void addDcimFolder(String path) {
        synchronized (lock){
            if(dcimFolderList == null) {
                dcimFolderList = new ArrayList<>();
            }

            if(dcimFolderList.size() > 0) {
                for(int i = 0; i < dcimFolderList.size(); i++) {
                    if(path.equals(dcimFolderList.get(i))) {
                        return;
                    }
                }
            }

            dcimFolderList.add(path);
        }
    }

    public static void delDcimFolder(String path) {
        synchronized (lock){
            if(dcimFolderList != null && dcimFolderList.size() != 0) {
                for(int i = 0; i < dcimFolderList.size(); i++) {
                    if(path.equals(dcimFolderList.get(i))) {
                        dcimFolderList.remove(i);
                    }
                }

            }
        }
    }

    private static void addCustomFolders(File customFile) {
        if(customFile.exists() && customFile.listFiles()!=null && customFile.listFiles().length > 0) {
            File[] var4;
            int var3 = (var4 = customFile.listFiles()).length;

            for(int var2 = 0; var2 < var3; ++var2) {
                File temp = var4[var2];
                if(temp.isDirectory()) {
                    addDcimFolder(temp.getPath());
                }
            }
        }

    }

    private static final void refreshDirtySets(Context context) {
        byte[] existingData = sAlbumCache.get(-4L, 0L);
        if(existingData != null && existingData.length > 0) {
            long[] ids = toLongArray(existingData);
            int numIds = ids.length;
            if(numIds > 0) {
                ArrayList<MediaSet> sets = new ArrayList(numIds);
                LongSparseArray<MediaSet> acceleratedSets = new LongSparseArray(numIds);

                for(int i = 0; i < numIds; i++) {
                    MediaSet set = new MediaSet();
                    set.mId = ids[i];
                    sets.add(set);
                    acceleratedSets.put(set.mId, set);
                }

                Log.i("CacheService", "Refreshing dirty albums");
                populateMediaItemsForSets(context, sets, acceleratedSets, true);
                Thread.interrupted();
            }
        }

        sAlbumCache.delete(-4L);
    }

    public static final long[] computeDirtySets(Context context) {
        Uri uriImages = Media.EXTERNAL_CONTENT_URI;
        Uri uriVideos = android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        ContentResolver cr = context.getContentResolver();
        String where = "bucket_id!=0) GROUP BY (bucket_id ";
        ArrayList retVal = new ArrayList();

        try {
            Cursor cursorImages = cr.query(uriImages, SENSE_PROJECTION, "bucket_id!=0) GROUP BY (bucket_id ", (String[])null, (String)null);
            Cursor cursorVideos = cr.query(uriVideos, SENSE_PROJECTION, "bucket_id!=0) GROUP BY (bucket_id ", (String[])null, (String)null);
            Cursor[] cursors = new Cursor[]{cursorImages, cursorVideos};
            MergeCursor cursor = new MergeCursor(cursors);

            try {
                if(cursor.moveToFirst()) {
                    boolean allDirty = false;

                    do {
                        long setId = cursor.getLong(0);
                        if(allDirty) {
                            addNoDupe(retVal, setId);
                        } else {
                            boolean contains = sAlbumCache.isDataAvailable(setId, 0L);
                            if(!contains) {
                                markDirty(context);
                                addNoDupe(retVal, setId);
                                allDirty = true;
                            }

                            if(!allDirty) {
                                long maxAdded = cursor.getLong(1);
                                int count = cursor.getInt(2);
                                byte[] data = sMetaAlbumCache.get(setId, 0L);
                                long[] dataLong = new long[2];
                                if(data != null) {
                                    dataLong = toLongArray(data);
                                }

                                long oldMaxAdded = dataLong[0];
                                long oldCount = dataLong[1];
                                if(maxAdded > oldMaxAdded || oldCount != (long)count) {
                                    markDirty(context, setId);
                                    addNoDupe(retVal, setId);
                                    dataLong[0] = maxAdded;
                                    dataLong[1] = (long)count;
                                    sMetaAlbumCache.put(setId, longArrayToByteArray(dataLong), 0L);
                                }
                            }
                        }
                    } while(cursor.moveToNext());
                }
            } finally {
                cursor.close();
            }

            sMetaAlbumCache.flush();
        } catch (Exception var27) {
            ;
        }

        int numIds = retVal.size();
        long[] retValIds = new long[numIds];

        for(int i = 0; i < numIds; i++) {
            retValIds[i] = ((Long)retVal.get(i)).longValue();
        }

        return retValIds;
    }

    private static final void addNoDupe(ArrayList<Long> array, long value) {
        int size = array.size();

        for(int i = 0; i < size; i++) {
            if(((Long)array.get(i)).longValue() == value) {
                return;
            }
        }

        array.add(Long.valueOf(value));
    }

    private static final void processQueuedDirty(Context context) {
        do {
            if(QUEUE_DIRTY_SENSE) {
                QUEUE_DIRTY_SENSE = false;
                QUEUE_DIRTY_ALL = false;
                QUEUE_DIRTY_SET = false;
                computeDirtySets(context);
            } else if(QUEUE_DIRTY_ALL) {
                QUEUE_DIRTY_ALL = false;
                QUEUE_DIRTY_SET = false;
                QUEUE_DIRTY_SENSE = false;
                refresh(context);
            } else if(QUEUE_DIRTY_SET) {
                QUEUE_DIRTY_SET = false;
                refreshDirtySets(context);
            }
        } while(QUEUE_DIRTY_SENSE || QUEUE_DIRTY_SET || QUEUE_DIRTY_ALL);

    }

    private static final void populateMediaItemsForSets(Context context, ArrayList<MediaSet> sets, LongSparseArray<MediaSet> acceleratedSets, boolean useWhere) {
        if(sets != null && sets.size() != 0 && !Thread.interrupted()) {
            Log.i("CacheService", "Building items.");
            Uri uriImages = Media.EXTERNAL_CONTENT_URI;
            ContentResolver cr = context.getContentResolver();
            String whereClause = null;
            if(useWhere) {
                int numSets = sets.size();
                StringBuffer whereString = new StringBuffer("bucket_id in (");

                for(int i = 0; i < numSets; i++) {
                    whereString.append(((MediaSet)sets.get(i)).mId);
                    if(i != numSets - 1) {
                        whereString.append(",");
                    }
                }

                whereString.append(")");
                whereClause = whereString.toString();
                Log.i("CacheService", "Updating dirty albums where " + whereClause);
            }

            try {
                label204: {
                    Cursor cursorImages = cr.query(uriImages, PROJECTION_IMAGES, whereClause, (String[])null, DEFAULT_IMAGE_SORT_ORDER);
                    Cursor[] cursors = new Cursor[]{cursorImages};
                    SortCursor sortCursor = new SortCursor(cursors, "datetaken", 1, true);
                    if(Thread.interrupted()) {
                        return;
                    }

                    try {
                        if(sortCursor == null || !sortCursor.moveToFirst()) {
                            break label204;
                        }

                        int count = sortCursor.getCount();
                        int numSets = sets.size();
                        int approximateCountPerSet = count / numSets;

                        for(int i = 0; i < numSets; i++) {
                            MediaSet set = (MediaSet)sets.get(i);
                            set.setNumExpectedItems(approximateCountPerSet);
                        }

                        while(!Thread.interrupted()) {
                            MediaItem item = new MediaItem();
                            boolean isVideo = sortCursor.getCurrentCursorIndex() == 1;
                            if(isVideo) {
                                populateVideoItemFromCursor(item, cr, sortCursor, BASE_CONTENT_STRING_VIDEOS);
                            } else {
                                populateMediaItemFromCursor(item, cr, sortCursor, BASE_CONTENT_STRING_IMAGES);
                            }

                            long setId = sortCursor.getLong(10);
                            MediaSet set = findSet(setId, acceleratedSets);
                            if(set != null) {
                                set.addItem(item);
                            }

                            if(!sortCursor.moveToNext()) {
                                break label204;
                            }
                        }
                    } finally {
                        if(sortCursor != null) {
                            sortCursor.close();
                        }

                    }

                    return;
                }
            } catch (Exception var22) {
                ;
            }

            if(sets.size() > 0) {
                writeItemsToCache(sets);
                Log.i("CacheService", "Done building items.");
            }

        }
    }

    private static final void writeSetsToCache(ArrayList<MediaSet> sets) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int numSets = sets.size();
        DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(bos, 256));

        try {
            dos.writeInt(numSets);

            for(int i = 0; i < numSets; i++) {
                if(Thread.interrupted()) {
                    return;
                }

                MediaSet set = (MediaSet)sets.get(i);
                dos.writeLong(set.mId);
                Utils.writeUTF(dos, set.mName);
                dos.writeBoolean(set.mHasImages);
                dos.writeBoolean(set.mHasVideos);
            }

            dos.flush();
            sAlbumCache.put(-1L, bos.toByteArray(), 0L);
            dos.close();
            if(numSets == 0) {
                sAlbumCache.deleteAll();
                putLocaleForAlbumCache(Locale.getDefault());
            }

            sAlbumCache.flush();
        } catch (IOException var6) {
            Log.e("CacheService", "Error writing albums to diskcache.");
            sAlbumCache.deleteAll();
            putLocaleForAlbumCache(Locale.getDefault());
        }

    }

    private static final void writeItemsToCache(ArrayList<MediaSet> sets) {
        int numSets = sets.size();

        for(int i = 0; i < numSets; i++) {
            if(Thread.interrupted()) {
                return;
            }

            writeItemsForASet((MediaSet)sets.get(i));
        }

        sAlbumCache.flush();
    }

    private static final void writeItemsForASet(MediaSet set) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(bos, 256));

        try {
            ArrayList<MediaItem> items = set.getItems();
            int numItems = items.size();
            dos.writeInt(numItems);
            dos.writeLong(set.mMinTimestamp);
            dos.writeLong(set.mMaxTimestamp);

            for(int i = 0; i < numItems; i++) {
                MediaItem item = (MediaItem)items.get(i);
                if(set.mId == (long)CAMERA_BUCKET_ID || set.mId == (long)DOWNLOAD_BUCKET_ID) {
                    item = (MediaItem)items.get(numItems - i - 1);
                }

                dos.writeLong(item.mId);
                Utils.writeUTF(dos, item.mCaption);
                Utils.writeUTF(dos, item.mMimeType);
                dos.writeInt(item.getMediaType());
                dos.writeDouble(item.mLatitude);
                dos.writeDouble(item.mLongitude);
                dos.writeLong(item.mDateTakenInMs);
                dos.writeBoolean(item.mTriedRetrievingExifDateTaken);
                dos.writeLong(item.mDateAddedInSec);
                dos.writeLong(item.mDateModifiedInSec);
                dos.writeInt(item.mDurationInSec);
                dos.writeInt((int)item.mRotation);
                Utils.writeUTF(dos, item.mFilePath);
            }

            dos.flush();
            sAlbumCache.put(set.mId, bos.toByteArray(), 0L);
            dos.close();
        } catch (IOException var7) {
            Log.e("CacheService", "Error writing to diskcache for set " + set.mName);
            sAlbumCache.deleteAll();
            putLocaleForAlbumCache(Locale.getDefault());
        }

    }

    private static final MediaSet findSet(long id, LongSparseArray<MediaSet> acceleratedTable) {
        return (MediaSet)acceleratedTable.get(id);
    }

    private static int getBucketId(String path) {
        return path.toLowerCase().hashCode();
    }

    private static void deleSDFolder(File file) {
        if(file.exists()) {
            if(file.listFiles().length > 0) {
                File[] var4;
                int var3 = (var4 = file.listFiles()).length;

                for(int var2 = 0; var2 < var3; ++var2) {
                    File temp = var4[var2];
                    if(temp.isDirectory()) {
                        deleSDFolder(temp);
                    } else {
                        temp.delete();
                    }
                }
            }

            file.delete();
        }

    }

    public static void clearCache() {
        sAlbumCache.deleteAll();
        sMetaAlbumCache.deleteAll();
        sSkipThumbnailIds.deleteAll();
        sThumbnailCache.deleteAll();
        sThumbnailCacheVideo.deleteAll();
        File file = new File(getCachePath());
        deleSDFolder(file);
    }
}
